use std::fs;
use std::path::PathBuf;
use uuid::Uuid;
use tauri::command;
use dirs_next::config_dir; // 用于获取系统配置目录
use reqwest::Client;
use crate::controller::response::ApiResponse;
use crate::controller::setting::{ ProxyConfig};
use crate::controller::setting;

// ---------- 配置文件路径 ----------
fn config_file_path() -> PathBuf {
    let mut path = config_dir().unwrap_or_else(|| PathBuf::from("."));
    path.push("frp-tauri"); // 应用子目录
    fs::create_dir_all(&path).ok();
    path.push("config.json");
    path
}


// ---------- 保存配置 ----------



// ---------- 代理操作命令 ---------- //

#[command]
pub fn add_proxie(mut proxy: ProxyConfig) -> ApiResponse<Vec<ProxyConfig>> {
    use crate::controller::setting;

    // 1. 修改 id 和 status
    proxy.id = Uuid::new_v4().to_string();
    proxy.status = 1;

    // 2. 获取现有 proxies
    let proxies_api = setting::get_setting("client.config.proxies");
    if !proxies_api.code == 0 {
        return ApiResponse::fail(
            format!("获取 proxies 失败: {}", proxies_api.msg),
            None,
        );
    }

    let mut proxies: Vec<ProxyConfig> = match serde_json::from_value(proxies_api.data.unwrap_or_default()) {
        Ok(p) => p,
        Err(e) => return ApiResponse::fail(format!("解析 proxies 失败: {}", e), None),
    };

    // 3. 追加新的 proxy
    proxies.push(proxy);

    // 4. 保存
    let save_api = setting::set_setting(
        "client.config.proxies",
        serde_json::to_value(&proxies).unwrap(),
    );

    if !save_api.code == 0 {
        return ApiResponse::fail(
            format!("保存 proxies 失败: {}", save_api.msg),
            None,
        );
    }

    // 5. 返回新的列表
    ApiResponse::ok("success", Some(proxies))
}

#[command]
pub fn del_proxie(id: String) -> ApiResponse<()> {
    // 1. 获取现有 proxies
    let result = setting::get_setting("client.config.proxies");

    if result.code != 1 {
        return ApiResponse::fail(
            format!("获取 proxies 失败: {}", result.msg),
            None,
        );
    }

    // 2. 解包 data
    let mut proxies: Vec<setting::ProxyConfig> = match result.data {
        Some(data) => match serde_json::from_value(data) {
            Ok(p) => p,
            Err(e) => return ApiResponse::fail(format!("解析 proxies 失败: {}", e), None),
        },
        None => return ApiResponse::fail("proxies 数据为空", None),
    };

    // 3. 删除指定 id 的 proxy
    proxies.retain(|p| p.id != id);

    // 4. 保存修改后的 proxies
    let save_result = setting::set_setting(
        "client.config.proxies",
        serde_json::to_value(&proxies).unwrap(),
    );

    if save_result.code != 1 {
        return ApiResponse::fail(
            format!("保存 proxies 失败: {}", save_result.msg),
            None,
        );
    }

    ApiResponse::ok("删除成功", None)
}

#[command]
pub fn save_status(id: String, status: u16) -> ApiResponse<()> {
    // 1. 获取现有 proxies
    let result = setting::get_setting("client.config.proxies");

    if result.code != 1 {
        return ApiResponse::fail(
            format!("获取 proxies 失败: {}", result.msg),
            None,
        );
    }

    // 2. 解包 data
    let mut proxies: Vec<ProxyConfig> = match result.data {
        Some(data) => match serde_json::from_value(data) {
            Ok(p) => p,
            Err(e) => return ApiResponse::fail(format!("解析 proxies 失败: {}", e), None),
        },
        None => return ApiResponse::fail("proxies 数据为空", None),
    };

    // 3. 查找并修改 status
    let mut found = false;
    for p in proxies.iter_mut() {
        if p.id == id {
            p.status = status as i32;
            found = true;
            break;
        }
    }

    if !found {
        return ApiResponse::fail(format!("未找到 id 为 {} 的 proxy", id), None);
    }

    // 4. 保存修改后的 proxies
    let save_result = setting::set_setting(
        "client.config.proxies",
        serde_json::to_value(&proxies).unwrap(),
    );

    if save_result.code != 1 {
        return ApiResponse::fail(
            format!("保存 proxies 失败: {}", save_result.msg),
            None,
        );
    }

    // 5. 返回最新列表
    ApiResponse::ok("状态更新成功", None)
}


#[command]
pub fn save_proxie(proxy: ProxyConfig) -> ApiResponse<()> {
    // 1. 获取现有 proxies
    let result = setting::get_setting("client.config.proxies");
    if result.code == 0 {
        return ApiResponse::fail(format!("获取 proxies 失败: {}", result.msg), None);
    }

    let proxies_value = match result.data {
        Some(v) => v,
        None => return ApiResponse::fail("proxies 配置为空", None),
    };

    let mut proxies: Vec<ProxyConfig> = match serde_json::from_value(proxies_value) {
        Ok(p) => p,
        Err(e) => return ApiResponse::fail(format!("解析 proxies 失败: {}", e), None),
    };

    // 2. 查找并更新
    let mut found = false;
    for p in proxies.iter_mut() {
        if p.id == proxy.id {
            // 保持 id 和 status 不变，更新其他字段
            p.name = proxy.name.clone();
            p.custom_domains = proxy.custom_domains.clone();
            p.local_ip = proxy.local_ip.clone();
            p.local_port = proxy.local_port;
            p.proxy_type = proxy.proxy_type.clone();
            found = true;
            break;
        }
    }

    if !found {
        return ApiResponse::fail(format!("未找到 id={} 的代理", proxy.id), None);
    }

    // 3. 保存
    let save_result = setting::set_setting(
        "client.config.proxies",
        serde_json::to_value(&proxies).unwrap(),
    );

    if save_result.code == 0 {
        return ApiResponse::fail(format!("保存失败: {}", save_result.msg), None);
    }

    ApiResponse::ok("保存成功", None)
}


// ---------- frpc.toml 文件路径 ----------
fn frpc_file_path() -> PathBuf {
    let mut path = config_dir().unwrap_or_else(|| PathBuf::from("."));
    path.push("frp-tauri");
    fs::create_dir_all(&path).ok();
    path.push("frpc.toml");
    path
}

// ---------- 异步刷新服务方法 ----------
#[command]
pub async fn restart_server() -> Result<(), String> {
//     // 1. 加载配置
//     let cfg: create::setting::ClientConfig = crate::setting::get_setting("client").await;

//     // 2. 构造 frpc.toml 内容
//     let mut toml_content = format!(
//         r#"serverAddr = "{}"
// serverPort = {}

// webServer.addr = "{}"
// webServer.port = {}
// webServer.user = ""
// webServer.password = ""
// "#,
//         cfg.server_addr,
//         cfg.server_port,
//         cfg.server_addr,
//         7400 // webServer port，可以改成动态
//     );

//     for proxy in cfg.proxies {
//         if proxy.status != 1 {
//             continue;
//         }
//         let domains = proxy
//             .custom_domains
//             .iter()
//             .map(|d| format!(r#""{}""#, d))
//             .collect::<Vec<_>>()
//             .join(", ");
//         let section = format!(
//             r#"
// [[proxies]]
// name = "{}"
// type = "{}"
// localIP = "{}"
// localPort = {}
// customDomains = [{}]
// "#,
//             proxy.name, proxy.proxy_type, proxy.local_ip, proxy.local_port, domains
//         );
//         toml_content.push_str(&section);
//     }

//     // 3. 写入 frpc.toml 文件（同步写入即可）
//     let frpc_path = frpc_file_path();
//     fs::write(&frpc_path, &toml_content).map_err(|e| e.to_string())?;

//     // 4. 异步 HTTP 请求
//     let client = Client::new();
//     let url = format!("http://{}:{}/api/reload", cfg.server_addr, cfg.server_port);
//     let res = client
//         .get(&url)
//         .header("Content-Type", "text/plain")
//         .send()
//         .await
//         .map_err(|e| e.to_string())?;

//     if res.status().is_success() {
//         Ok(())
//     } else {
//         Err(format!("刷新失败，HTTP 状态码: {}", res.status()))
//     }
    Ok(())
}
